package cn.wink.springcloud.controller;

import cn.wink.springcloud.entites.Payment;
import cn.wink.springcloud.service.PaymentService;
import cn.wink.springcloud.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xw
 * @date 2020-05-02 10:56
 */
@Slf4j
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 服务发现：获得所有服务信息
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/create")
    public Result create(@RequestBody Payment payment) {
        int insert = paymentService.insert(payment);
        log.info("插入条数：{},端口号：{}", insert, serverPort);
        return Result.ok(insert);
    }

    @GetMapping("/get/{id}")
    public Result getById(@PathVariable("id") Long id) {
        Payment payment = paymentService.selectByPrimaryKey(id);
        log.info("查询数据为：{},端口号：{}", payment, serverPort);
        Map<String,Object> map = new HashMap<>();
        map.put("payment",payment);
        map.put("serverPort",serverPort);
        return Result.ok(map);
    }

    @GetMapping("/discovery")
    public Result discovery() {
        //获得所有微服务
        List<String> services = discoveryClient.getServices();
        services.forEach(a -> log.info("服务名：{}", a));
        //一个微服务的所有实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(instance -> log.info("实例信息：{}", instance.getHost()));
        return Result.ok(discoveryClient);
    }

    @GetMapping("/zipkin")
    public String paymentZipkin() {
        return "hi ,i'am paymentzipkin server fall back，welcome to atguigu，O(∩_∩)O哈哈~";
    }
}
